package routers

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"seawolf-admin-go/utility/db"
	"strings"
	"time"
)

// MiddlewareErrorHandler 入参打印日志
func MiddlewareErrorHandler(r *ghttp.Request) {
	r.Response.CORSDefault()
	ctx := r.GetCtx()
	if strings.Index(r.Request.URL.Path, "/upload") == -1 {
		// 不是上传的方法才打印
		g.Log().Async().Cat("router").Debug(ctx, "路由："+r.Request.URL.Path)
		g.Log().Async().Cat("router").Debug(ctx, "Query："+r.Request.URL.RawQuery)
		g.Log().Async().Cat("router").Debug(ctx, "body：\n"+r.GetBodyString())
	}

	r.Middleware.Next()

	//fmt.Println(gtime.Now().String() + " MiddlewareErrorHandler")
	// 记录请求日志
	//go addRequestLog(r)
}

func addRequestLog(r *ghttp.Request) {
	if strings.Index(r.Request.URL.Path, "/upload") != -1 {
		return
	}
	if strings.Index(r.Request.URL.Path, "/captcha") != -1 {
		return
	}
	ctx := r.GetCtx()
	_, err := db.GetUnSafaTable(ctx, "api_request_log").Data(g.Map{
		"user_id":     r.GetCtxVar("admin_id").Int(),
		"request_id":  gctx.CtxId(r.Context()),
		"method_type": r.Request.Method,
		"route":       r.Request.URL.Path,
		"token":       r.Request.Header.Get("token"),
		//"header_data": r.Request.Header, // 请求头，只收集部分
		"param_data":      r.GetMap(),
		"version":         r.Request.Header.Get("version"),
		"response_status": r.Response.Status,
		"ip":              r.GetRemoteIp(),
		"in_at":           time.Now().UnixNano() / 1e6,
	}).Insert()
	if err != nil {
		g.Log().Async().Cat("router").Error(ctx, "记录请求日志失败")
		return
	}
}
